/**
 * 创建 OKR 弹窗组件
 * 用于创建新的 OKR 目标节点
 */

import React, { useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import {
  Modal,
  Form,
  Input,
  Select,
  DatePicker,
  Button,
  Space,
  Card,
  InputNumber,
  message,
  Divider,
  Typography
} from "antd";
import { PlusOutlined, DeleteOutlined } from "@ant-design/icons";
import dayjs from "dayjs";
import type { AppDispatch } from "../../../store";
import { createOKRNode, selectOKRNodes } from "../../../store/okrSlice";
import type { CreateOKRNodeRequest } from "../../../types/okr";
import { OKRNodeType, OKRStatus } from "../../../types/okr";

const { TextArea } = Input;
const { Title } = Typography;
const { RangePicker } = DatePicker;

interface CreateOKRModalProps {
  /** 是否显示弹窗 */
  visible: boolean;
  /** 当前季度 */
  quarter: string;
  /** 关闭弹窗回调 */
  onClose: () => void;
  /** 创建成功回调 */
  onSuccess: () => void;
}

interface KeyResultFormData {
  title: string;
  description: string;
  targetValue: number;
  unit: string;
  deadline: string;
}

/**
 * 创建 OKR 弹窗组件
 */
const CreateOKRModal: React.FC<CreateOKRModalProps> = ({ visible, quarter, onClose, onSuccess }) => {
  const dispatch = useDispatch<AppDispatch>();
  const nodes = useSelector(selectOKRNodes);
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [keyResults, setKeyResults] = useState<KeyResultFormData[]>([]);

  /**
   * 获取可用的父节点选项
   */
  const getParentNodeOptions = () => {
    const options: Array<{ label: string; value: string | undefined }> = [
      { label: "无（创建根节点）", value: undefined }
    ];

    Object.values(nodes).forEach(node => {
      // 只有部门和团队节点可以作为父节点
      if (node.type === OKRNodeType.DEPARTMENT || node.type === OKRNodeType.TEAM) {
        options.push({
          label: `${node.title} (${getNodeTypeName(node.type)})`,
          value: node.id
        });
      }
    });

    return options;
  };

  /**
   * 获取节点类型显示名称
   */
  const getNodeTypeName = (type: OKRNodeType) => {
    switch (type) {
      case OKRNodeType.DEPARTMENT:
        return "部门目标";
      case OKRNodeType.TEAM:
        return "团队目标";
      case OKRNodeType.INDIVIDUAL:
        return "个人目标";
      default:
        return "目标";
    }
  };

  /**
   * 添加关键结果
   */
  const addKeyResult = () => {
    setKeyResults([
      ...keyResults,
      {
        title: "",
        description: "",
        targetValue: 100,
        unit: "%",
        deadline: dayjs().add(3, "month").format("YYYY-MM-DD")
      }
    ]);
  };

  /**
   * 删除关键结果
   */
  const removeKeyResult = (index: number) => {
    setKeyResults(keyResults.filter((_, i) => i !== index));
  };

  /**
   * 更新关键结果
   */
  const updateKeyResult = (index: number, field: keyof KeyResultFormData, value: any) => {
    const newKeyResults = [...keyResults];
    newKeyResults[index] = {
      ...newKeyResults[index],
      [field]: value
    };
    setKeyResults(newKeyResults);
  };

  /**
   * 处理表单提交
   */
  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();

      // 验证关键结果
      for (const kr of keyResults) {
        if (!kr.title.trim()) {
          message.error("请填写所有关键结果的标题");
          return;
        }
        if (kr.targetValue <= 0) {
          message.error("关键结果的目标值必须大于0");
          return;
        }
      }

      setLoading(true);

      const createData: CreateOKRNodeRequest = {
        title: values.title,
        description: values.description,
        type: values.type,
        parentId: values.parentId,
        ownerId: "current-user", // 在实际应用中应该从当前用户信息获取
        quarter,
        startDate: values.dateRange[0].format("YYYY-MM-DD"),
        endDate: values.dateRange[1].format("YYYY-MM-DD"),
        keyResults: keyResults.map(kr => ({
          title: kr.title,
          description: kr.description,
          targetValue: kr.targetValue,
          currentValue: 0,
          unit: kr.unit,
          progress: 0,
          status: OKRStatus.NOT_STARTED,
          deadline: kr.deadline
        }))
      };

      await dispatch(createOKRNode(createData)).unwrap();
      message.success("创建成功");

      // 重置表单
      form.resetFields();
      setKeyResults([]);

      onSuccess();
    } catch (error) {
      message.error("创建失败");
    } finally {
      setLoading(false);
    }
  };

  /**
   * 处理弹窗关闭
   */
  const handleClose = () => {
    form.resetFields();
    setKeyResults([]);
    onClose();
  };

  return (
    <Modal
      title="创建 OKR 目标"
      open={visible}
      onCancel={handleClose}
      width={800}
      footer={
        <Space>
          <Button onClick={handleClose}>取消</Button>
          <Button type="primary" onClick={handleSubmit} loading={loading}>
            创建目标
          </Button>
        </Space>
      }
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          type: OKRNodeType.TEAM,
          dateRange: [dayjs(), dayjs().add(3, "month")]
        }}
      >
        {/* 基本信息 */}
        <div className="mb-6">
          <Title level={5}>基本信息</Title>

          <Form.Item name="title" label="目标标题" rules={[{ required: true, message: "请输入目标标题" }]}>
            <Input placeholder="请输入目标标题" />
          </Form.Item>

          <Form.Item name="description" label="目标描述" rules={[{ required: true, message: "请输入目标描述" }]}>
            <TextArea rows={3} placeholder="请详细描述这个目标的内容和期望达成的效果" />
          </Form.Item>

          <div className="grid grid-cols-2 gap-4">
            <Form.Item name="type" label="目标类型" rules={[{ required: true, message: "请选择目标类型" }]}>
              <Select placeholder="请选择目标类型">
                <Select.Option value={OKRNodeType.DEPARTMENT}>部门目标</Select.Option>
                <Select.Option value={OKRNodeType.TEAM}>团队目标</Select.Option>
                <Select.Option value={OKRNodeType.INDIVIDUAL}>个人目标</Select.Option>
              </Select>
            </Form.Item>

            <Form.Item name="parentId" label="上级目标">
              <Select placeholder="请选择上级目标（可选）" options={getParentNodeOptions()} allowClear />
            </Form.Item>
          </div>

          <Form.Item name="dateRange" label="目标周期" rules={[{ required: true, message: "请选择目标周期" }]}>
            <RangePicker style={{ width: "100%" }} format="YYYY-MM-DD" />
          </Form.Item>
        </div>

        <Divider />

        {/* 关键结果 */}
        <div>
          <div className="flex items-center justify-between mb-4">
            <Title level={5}>关键结果</Title>
            <Button type="dashed" icon={<PlusOutlined />} onClick={addKeyResult}>
              添加关键结果
            </Button>
          </div>

          {keyResults.length === 0 ? (
            <div className="text-center py-8 text-gray-500 bg-gray-50 rounded-lg">
              <div className="text-lg mb-2">🎯</div>
              <div>暂无关键结果</div>
              <div className="text-sm">点击上方按钮添加关键结果</div>
            </div>
          ) : (
            <div className="space-y-4">
              {keyResults.map((kr, index) => (
                <Card
                  key={index}
                  size="small"
                  title={`关键结果 ${index + 1}`}
                  extra={
                    <Button type="text" danger icon={<DeleteOutlined />} onClick={() => removeKeyResult(index)}>
                      删除
                    </Button>
                  }
                >
                  <div className="space-y-3">
                    <Input
                      placeholder="关键结果标题"
                      value={kr.title}
                      onChange={e => updateKeyResult(index, "title", e.target.value)}
                    />

                    <TextArea
                      rows={2}
                      placeholder="关键结果描述"
                      value={kr.description}
                      onChange={e => updateKeyResult(index, "description", e.target.value)}
                    />

                    <div className="grid grid-cols-3 gap-3">
                      <div>
                        <label className="block text-sm text-gray-600 mb-1">目标值</label>
                        <InputNumber
                          style={{ width: "100%" }}
                          placeholder="目标值"
                          value={kr.targetValue}
                          onChange={value => updateKeyResult(index, "targetValue", value || 0)}
                          min={0}
                        />
                      </div>

                      <div>
                        <label className="block text-sm text-gray-600 mb-1">单位</label>
                        <Select
                          style={{ width: "100%" }}
                          value={kr.unit}
                          onChange={value => updateKeyResult(index, "unit", value)}
                        >
                          <Select.Option value="%">%</Select.Option>
                          <Select.Option value="个">个</Select.Option>
                          <Select.Option value="次">次</Select.Option>
                          <Select.Option value="万元">万元</Select.Option>
                          <Select.Option value="人">人</Select.Option>
                          <Select.Option value="天">天</Select.Option>
                          <Select.Option value="小时">小时</Select.Option>
                        </Select>
                      </div>

                      <div>
                        <label className="block text-sm text-gray-600 mb-1">截止时间</label>
                        <Input
                          type="date"
                          value={kr.deadline}
                          onChange={e => updateKeyResult(index, "deadline", e.target.value)}
                        />
                      </div>
                    </div>
                  </div>
                </Card>
              ))}
            </div>
          )}
        </div>
      </Form>
    </Modal>
  );
};

export default CreateOKRModal;
